import React, { useContext, useState } from "react";
import classes from "./CartDetail.module.css";
import Backdrop from "../../../UI/Backdrop/Backdrop";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrash } from "@fortawesome/free-solid-svg-icons";
import CartContext from "../../../store/CardCountext";
import Meal from "../../Meals/Meal/Meal";
import Confirm from "../../../UI/Confirm/Confirm";

function CartDetail() {
    const ctx = useContext(CartContext);
    
    
    //处理清空购物车
    const [showConfirm, setShowConfirm] = useState(false);
    const clearHandler = () => {
        setShowConfirm(true);
    };
    const cancelHandler = (e,...refTargets) => {
        //防止冒泡到遮罩层
        e.stopPropagation();
        //判断是否是弹窗的内DOM元素，排除遮罩层
        for(const ref of refTargets){
            if(e.target === ref.current) return
        }
         
        setShowConfirm(false);
        
    };
    const okHandler = () => {
        ctx.clearCart()
    }

    return (
        <Backdrop>
            {showConfirm && (
                <Confirm
                    confirmText={"确认清空吗?"}
                    onCancel={cancelHandler}
                    onOk={okHandler}
                ></Confirm>
            )}

            <div
                className={classes.cartDetail}
                onClick={(e) => e.stopPropagation()}
            >
                <header className={classes.header}>
                    <h2 className={classes.title}>餐品详情</h2>
                    <div className={classes.clear} onClick={clearHandler}>
                        <FontAwesomeIcon icon={faTrash} />
                        <span>清空购物车</span>
                    </div>
                </header>
                <div>
                    {ctx.items.map((item) => (
                        <Meal key={item.id} meal={item} displayDesc={false} />
                    ))}
                </div>
            </div>
        </Backdrop>
    );
}

export default CartDetail;
